package com.nnnu.wsnackshop.controller.user;

import com.nnnu.wsnackshop.constant.MessageConstants;
import com.nnnu.wsnackshop.constant.StatusCodeConstants;
import com.nnnu.wsnackshop.controller.base.BaseController;
import com.nnnu.wsnackshop.pojo.vo.CouponVO;
import com.nnnu.wsnackshop.result.Result;
import com.nnnu.wsnackshop.service.IUserCouponsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户优惠券 控制器
 * </p>
 *
 * @author zk
 * @since 2025-05-14
 */
@RestController("userCouponsController")
@RequestMapping("/api/user/coupons")
@Tag(name = "用户优惠券接口", description = "用户优惠券相关的API")
@RequiredArgsConstructor
@Slf4j
public class CouponsController extends BaseController {

    private final IUserCouponsService userCouponsService;

    @Operation(summary = "获取当前用户的可用优惠券列表")
    @GetMapping("/my")
    public Result<List<CouponVO>> getMyCoupons() {
        if (!isLogin()) {
            return Result.error(StatusCodeConstants.UNAUTHORIZED, MessageConstants.NOT_LOGIN);
        }

        Integer userId = getUserId();
        log.info("用户{}查询优惠券列表", userId);

        try {
            List<CouponVO> coupons = userCouponsService.getUserAvailableCoupons(userId);
            return Result.success(coupons, "获取优惠券列表成功");
        } catch (Exception e) {
            log.error("获取优惠券列表失败: {}", e.getMessage());
            return Result.error(StatusCodeConstants.INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }

    @Operation(summary = "检查当前用户是否是首次登录（是否可领取新人券）")
    @GetMapping("/check-new-user")
    public Result<Map<String, Object>> checkNewUser() {
        if (!isLogin()) {
            return Result.error(StatusCodeConstants.UNAUTHORIZED, MessageConstants.NOT_LOGIN);
        }
        Integer userId = getUserId();
        log.info("检查用户{}是否可领取新人券", userId);

        try {
            boolean isFirstLogin = userCouponsService.isFirstLogin(userId);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("isNewUser", isFirstLogin);
            return Result.success(resultMap, "检查成功");
        } catch (Exception e) {
            log.error("检查新用户状态失败: {}", e.getMessage());
            return Result.error(StatusCodeConstants.INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
}
